<template>
  <div class="menus-manage">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>客户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <el-card class="box-card">
        <!-- 查询条件 -->
        <el-row class="table-selbox" v-if="btnSel">
          <!-- 查询条件表单 -->
          <el-form :inline="true" :model="formInline" >
            <!-- 客户名称 -->
            <el-form-item label="客户名称" prop="cusName">
              <el-select
                v-model="formInline.cusName"
                filterable
                auto-complete="off"
                placeholder="请选择"
              >
                <el-option label="无" value></el-option>
                <!-- 循环所有客户 客户名称 客户ID -->
                <el-option
                  v-for="(item,index) in cusList"
                  :key="index"
                  :label="item.cusName"
                  :value="item.cusName"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 客户分组 -->
            <el-form-item label="客户分组" prop="parentId">
              <el-select
                v-model="formInline.parentId"
                filterable
                auto-complete="off"
                placeholder="请选择"
              >
                 <el-option label="无" value></el-option>
                <!-- 循环所有客户 客户名称 客户ID -->
                <el-option
                  v-for="(item,index) in groupList"
                  :key="index"
                  :label="item.groupName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 搜索 -->
            <el-form-item>
              <el-button icon="el-icon-search" @click="selHandle">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <!-- 基本操作按钮 是否授权显示-->
        <el-row class="table-btns" v-if="[btnAdd,btnDel,btnUpload,btnDown].indexOf(true) > -1">
          <!-- 添加 -->
          <el-button
            v-if="btnAdd"
            type="success"
            size="medium"
            icon="el-icon-document-add"
            @click="addHandle"
          >添加</el-button>
          <!-- 删除 -->
          <el-button
            type="danger"
            size="medium"
            icon="el-icon-delete"
            @click="batchRemove"
            v-if="btnDel"
          >删除</el-button>
        </el-row>
        <!-- 数据列表 -->
        <el-table
          :data="menusData"
          border
          @selection-change="selsChange"
          style="width: 100%"
          height="395"
          ref="menusData"
        >
          <!-- 全选 -->
          <el-table-column type="selection" width="40" fixed></el-table-column>
          <!-- 客户名称 -->
          <el-table-column
            :show-overflow-tooltip="true"
            prop="cusName"
            label="客户名称"
            width="200"
            fixed
          ></el-table-column>
          <!-- 客户分组 -->
          <el-table-column label="客户分组" :show-overflow-tooltip="true" width="200" prop="groupName"></el-table-column>
          <!-- 客户类型 -->
          <el-table-column sortable label="客户类型" width="150" prop="cusType">
            <template slot-scope="scope">
              <span v-if="scope.row.cusType === '0' || scope.row.industry === null">无</span>
              <span v-else-if="scope.row.cusType === '1'">运营商</span>
              <span v-else-if="scope.row.cusType === '2'">广电</span>
              <span v-else>政企</span>
            </template>
          </el-table-column>
          <!-- 行业 -->
          <el-table-column label="客户行业" width="150" prop="industry" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span v-if="scope.row.industry === '0' || scope.row.industry === null">无</span>
              <span v-else-if="scope.row.industry === '1'">电信、广播电视和卫星传输服务</span>
              <span v-else-if="scope.row.industry === '2'">广播电影电视</span>
              <span v-else-if="scope.row.industry === '3'">网络通信</span>
              <span v-else-if="scope.row.industry === '4'">信息系统集成服务</span>
              <span v-else>软件和信息技术服务业</span>
            </template>
          </el-table-column>
          <!-- 信誉度 -->
          <el-table-column sortable label="信誉度" width="150" prop="credibility">
            <template slot-scope="scope">
              <span v-if="scope.row.credibility === 0 || scope.row.industry === null">无</span>
              <span v-else-if="scope.row.credibility === 1">高</span>
              <span v-else-if="scope.row.credibility === 2">中</span>
              <span v-else>低</span>
            </template>
          </el-table-column>
          <!-- 联络方式 -->
          <el-table-column label="联络方式" width="150" prop="contact"></el-table-column>
          <!-- 地址 -->
          <el-table-column label="地址" :show-overflow-tooltip="true" width="200" prop="address"></el-table-column>
          <!-- 备注说明 -->
          <el-table-column label="备注说明" :show-overflow-tooltip="true" prop="note"></el-table-column>
          <!-- 操作列 -->
          <el-table-column
            label="管理"
            fixed="right"
            align="center"
            width="340"
            v-if="[btnDel,btnEdit].indexOf(true) > -1"
          >
            <template slot-scope="scope">
              <!-- 删除 -->
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)" v-if="btnDel">删除</el-button>
              <!-- 修改 -->
              <el-button size="mini" @click="editHandle(scope.row)" v-if="btnEdit">修改</el-button>
              <!-- 授信表 -->
              <el-button size="mini" @click="mobilize(scope.row)" v-if="btnEdit">授信表</el-button>
              <!-- 通讯录 -->
              <el-button size="mini" @click="contact(scope.row)" v-if="btnEdit">通讯录</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="table-pageblock">
          <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20,50,80,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>
    </div>
    <!-- 弹窗 新增or修改 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <!-- 添加、修改表单 -->
      <el-form ref="editForm" :model="editForm" label-width="80px" :rules="editFormRules">
        <el-row :gutter="24">
          <el-col :span="12">
            <!-- 客户名称 -->
            <el-form-item label="客户名称" prop="cusName">
              <el-input v-model="editForm.cusName" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 客户分组 -->
            <el-form-item label="客户分组" prop="parentId">
              <el-select
                v-model="editForm.parentId"
                filterable
                auto-complete="off"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option label="无" value="0"></el-option>
                <!-- 循环所有客户 客户名称 客户ID -->
                <el-option
                  v-for="(item, index) in groupList"
                  :key="index"
                  :label="item.groupName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <!-- 客户类型 -->
            <el-form-item label="客户类型" prop="cusType">
              <el-select v-model="editForm.cusType" style="width:100%">
                <el-option label="无" value="0"></el-option>
                <el-option label="运营商" value="1"></el-option>
                <el-option label="广电" value="2"></el-option>
                <el-option label="政企" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 客户行业 -->
            <el-form-item label="客户行业" prop="industry">
              <el-select v-model="editForm.industry" style="width:100%">
                <el-option label="无" value="0"></el-option>
                <el-option label="电信、广播电视和卫星传输服务" value="1"></el-option>
                <el-option label="广播电影电视" value="2"></el-option>
                <el-option label="网络通信" value="3"></el-option>
                <el-option label="信息系统集成服务" value="4"></el-option>
                <el-option label="软件和信息技术服务业" value="5"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <!-- 信誉度 -->
            <el-form-item label="信誉度" prop="credibility">
              <el-select v-model="editForm.credibility" style="width:100%">
                <el-option label="无" value="0"></el-option>
                <el-option label="高" value="1"></el-option>
                <el-option label="中" value="2"></el-option>
                <el-option label="低" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 联系方式 -->
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="editForm.contact" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 地址 -->
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" auto-complete="off"></el-input>
        </el-form-item>
        <!-- 备注说明 -->
        <el-form-item label="备注说明" prop="note">
          <el-input type="textarea" placeholder="备注说明" v-model="editForm.note"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- 取消 关闭弹窗 -->
        <el-button @click.native="dialogFormVisible=false">取消</el-button>
        <!-- 添加 清空表单初始数据 -->
        <el-button
          v-if="dialogStatus=='create'"
          type="primary"
          @click="createData"

        >添加</el-button>
        <!-- 修改获取表单初始数据 -->
        <el-button v-else type="primary" @click="editData" >修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { _debounce } from '@/public/debounce.js';
export default {
  // 父组件传值子组件
  props: {
    // 按钮级权限
    btns: {
      type: Object
    }
  },

  // 无白屏刷新方法注入
  inject: ['reload'],

  // 监听
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    }
  },

  // 当前页面数据
  data () {
    return {

      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,

      // 搜索条件
      formInline: {
        cusName: '',
        parentId: ''
      },

      cusList: [],

      groupList: [],

      // 列表数据
      menusData: [{}],
      // 当前页
      currentPage: 1,
      // 当前数
      pageSize: 20,
      // 总条目数
      total: 20,

      // 弹窗类别
      dialogStatus: '',

      // 弹窗标题
      textMap: {
        edit: '修改信息',
        create: '添加信息'
      },
      // 弹窗是否显示
      dialogFormVisible: false,

      // 列表选中列
      sels: [],

      // 编辑界面输入框校验规则
      editFormRules: {
        cusName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '请选择客户分组', trigger: 'change' }
        ]
      },

      // 界面默认数据
      editForm: {
        cusName: '',
        parentId: '',
        cusType: '',
        industry: '',
        credibility: '',
        contact: '',
        address: '',
        note: ''
      }
    };
  },

  // 实例创建后执行
  created () {
    // 按钮级授权
    this.authorization(this.$store.state.btns);

    // 获取所有客户
    this.getProlist();

    // 加载分页数据
    this.getmenusDataByPage();
  },

  methods: {

    // 跳转客户授信表
    mobilize (data) {
      this.$router.push({
        path: '/home/credibility',
        query: {
          id: data.id
        }
      });
    },

    // 跳转客户通讯录
    contact (data) {
      this.$router.push({
        path: '/home/contact',
        query: {
          id: data.id
        }
      });
    },

    // 按钮级授权
    authorization (data) {
      let _this = this;
      for (let i in data) {
        if (data['sel'] === 0) {
          _this.btnSel = false;
        }
        if (data['add'] === 0) {
          _this.btnAdd = false;
        }
        if (data['del'] === 0) {
          _this.btnDel = false;
        }
        if (data['upload'] === 0) {
          _this.btnUpload = false;
        }
        if (data['down'] === 0) {
          _this.btnDown = false;
        }
        if (data['edit'] === 0) {
          _this.btnEdit = false;
        }
        return i;
      }
    },

    // 获取所有客户
    getProlist () {
      let _this = this;
      // 获取所有客户数据
      _this.$http.raw('api/findAllCus').then(res => {
        let { code, datas } = res;
        if (code === 0) {
          _this.cusList = datas;
          // 根据项目ID获取分页数据
          _this.$http.post('api/findAllGroup').then(res => {
            let { code, datas } = res;
            if (code === 0) {
              // 数据结果集
              _this.groupList = datas;
            }
          }).catch(err => {
            if (err === undefined) {
              _this.$message({
                message: '服务器响应异常！',
                type: 'error'
              });
              return false;
            }
          });
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 查询
    selHandle: function () {
      let _this = this;
      // 收集请求数据
      let params = {
        cusName: _this.formInline.cusName === null ? '' : _this.formInline.cusName,
        parentId: _this.formInline.parentId === null ? '0' : _this.formInline.parentId,
        pageNum: _this.currentPage,
        pageSize: _this.pageSize
      };
      // 根据项目ID获取分页数据
      _this.$http.raw('api/findCusByCusName', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 总页数
          _this.total = datas.total;
          // 数据结果集
          _this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 刷新页面数据
    getmenusDataByPage () {
      let _this = this;
      // 收集请求信息
      let params = {
        cusName: '',
        parentId: '',
        pageNum: _this.currentPage,
        pageSize: _this.pageSize
      };
      // 获取分页数据
      _this.$http.raw('api/findCusByCusName', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          _this.total = datas.total;
          _this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 每页显示的条数改变
    handleSizeChange (val) {
      this.pageSize = val;
      // 调用刷新页面
      this.getmenusDataByPage();
    },
    // 当前页码
    handleCurrentChange (val) {
      this.currentPage = val;
      // 调用
      this.getmenusDataByPage();
    },

    // 显示编辑界面
    editHandle: function (row) {
      let _this = this;
      // 弹窗类型
      _this.dialogStatus = 'edit';
      // 弹窗显示状态
      _this.dialogFormVisible = true;
      // 弹出窗表单初始值赋值
      _this.editForm = Object.assign({}, row);
      // 弹出窗表单 数据类型转换
      _this.editForm.cusType = row.cusType === null ? '0' : row.cusType.toString();
      _this.editForm.parentId = row.parentId === null ? '0' : row.parentId;
      // 客户行业
      _this.editForm.industry = row.industry === null ? '0' : row.industry.toString();
      // 信誉度
      _this.editForm.credibility = row.credibility === null ? '0' : row.credibility.toString();
    },

    // 显示新增界面
    addHandle: function () {
      let _this = this;
      // 弹窗类型
      _this.dialogStatus = 'create';
      // 弹窗显示状态
      _this.dialogFormVisible = true;

      // 初始化新增界面默认数据
      _this.editForm = {
        cusName: '',
        parentId: '',
        cusType: '',
        industry: '',
        credibility: '',
        contact: '',
        address: '',
        note: ''
      };
    },
    // 修改
    editData: _debounce(function () {
      let _this = this;
      _this.$nextTick(() => {
        // 判断是否通过验证规则验证
        _this.$refs['editForm'].validate(valid => {
          if (valid) {
            // 收集请求数据
            let params = {
              id: _this.editForm.id,
              cusName: _this.editForm.cusName === null ? '' : _this.editForm.cusName,
              cusType: _this.editForm.cusType === null ? '0' : _this.editForm.cusType,
              industry: _this.editForm.industry === null ? '0' : _this.editForm.industry,
              contact: _this.editForm.contact === null ? '' : _this.editForm.contact,
              address: _this.editForm.address === null ? '' : _this.editForm.address,
              note: _this.editForm.note === null ? '' : _this.editForm.note,
              parentId: _this.editForm.parentId === null ? '0' : _this.editForm.parentId,
              credibility: _this.editForm.credibility === null ? '0' : _this.editForm.credibility
            };

            // 修改用户信息
            _this.$http.raw('api/updateCustom', params).then(res => {
              let { code } = res;
              // 判断Code状态
              if (code === 0) {
                _this.$message({
                  message: '修改成功！',
                  type: 'success'
                });
                // 初始化弹出窗表单数据
                _this.$refs['editForm'].resetFields();
                // 关闭弹窗
                _this.dialogFormVisible = false;
                // 刷新列表
                _this.getmenusDataByPage();
                _this.getProlist();
              }
            }).catch(err => {
              if (err === undefined) {
                _this.$message({
                  message: '服务器响应异常！',
                  type: 'error'
                });
                return false;
              }
            });
          }
        });
      });
    }, 200),

    // 添加
    createData: _debounce(function () {
      let _this = this;
      _this.$nextTick(() => {
        // 判断是否通过验证规则验证
        _this.$refs['editForm'].validate(valid => {
          if (valid) {
            // 收集请求参数
            let params = {
              cusName: _this.editForm.cusName === null ? '' : _this.editForm.cusName,
              cusType: _this.editForm.cusType === null ? '0' : _this.editForm.cusType,
              industry: _this.editForm.industry === null ? '0' : _this.editForm.industry,
              contact: _this.editForm.contact === null ? '' : _this.editForm.contact,
              address: _this.editForm.address === null ? '' : _this.editForm.address,
              note: _this.editForm.note === null ? '' : _this.editForm.note,
              parentId: _this.editForm.parentId === null ? 0 : _this.editForm.parentId,
              credibility: _this.editForm.credibility === null ? '0' : _this.editForm.credibility
            };
            // 获取客户名称
            let getCus = {
              cusName: _this.editForm.cusName
            };
            // 通过客户名称判断是否被占用
            _this.$http.post('api/getCusCount', getCus).then(res => {
              let { code, datas } = res;
              // 判断Code状态
              if (code === 0) {
                if (datas) {
                  _this.$message({
                    message: '客户名称被占用！',
                    type: 'error'
                  });
                } else {
                  // 添加用户
                  _this.$http.raw('api/inserCustom', params).then(res => {
                    let { code } = res;
                    // 判断Code状态
                    if (code === 0) {
                      _this.$message({
                        message: '添加成功！',
                        type: 'success'
                      });
                      _this.$refs['editForm'].resetFields();
                      _this.dialogFormVisible = false;
                      // 刷新列表
                      _this.getmenusDataByPage();
                      _this.getProlist();
                    }
                  }).catch(err => {
                    if (err === undefined) {
                      _this.$message({
                        message: '服务器响应异常！',
                        type: 'error'
                      });
                      return false;
                    }
                  });
                }
              }
            }).catch(err => {
              if (err === undefined) {
                _this.$message({
                  message: '服务器响应异常！',
                  type: 'error'
                });
                return false;
              }
            });
          }
        });
      });
    }, 200),

    // 删除
    handleDelete (data) {
      let _this = this;
      // 二次删除确认
      _this.$confirm('确认删除选中的信息吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // 修改状态，逻辑删除
        let params = [data.id];
        // 根据数据ID删除对应用户信息
        _this.$http.raw('api/batchDelCustom', params).then(res => {
          let { code } = res;
          if (code === 0) {
            _this.$message({
              type: 'success',
              message: '删除成功！'
            });
            // 刷新列表
            _this.getmenusDataByPage();
            _this.getProlist();
          }
        }).catch(err => {
          if (err === undefined) {
            _this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }).catch(() => {
        _this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 全选、单选、多选
    selsChange: function (sels) {
      this.sels = sels;
    },

    // 批量删除
    batchRemove: function () {
      let _this = this;
      // 判断是否选择数据
      if (!_this.sels.length) {
        _this.$message.warning('您还没选择任何数据！');
        return;
      }
      // 二次删除确认
      _this.$confirm('确认删除选中的信息吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // 修改状态，逻辑删除
        let params = [];
        // 获取选中数据ID集合
        _this.sels.map(item => {
          return params.push(item.id);
        });
        // 删除对应ID用户信息
        _this.$http.raw('api/batchDelCustom', params).then(res => {
          let { code } = res;
          if (code === 0) {
            _this.$message({
              type: 'success',
              message: '批量删除成功！'
            });
            // 刷新列表
            _this.getmenusDataByPage();
            _this.getProlist();
          }
        }).catch(err => {
          if (err === undefined) {
            _this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }).catch(() => {
        _this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
};
</script>

<style lang='scss' scoped>
@import './index.scss';
</style>
